package cn.xinfei.xdecision.nacos;

import com.alibaba.cloud.nacos.registry.NacosAutoServiceRegistration;
import com.alibaba.cloud.nacos.registry.NacosRegistration;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Data
@Slf4j
@Service(value = "customerNacosAutoServiceRegistration")
@ConfigurationProperties(prefix = "spring.cloud.nacos.discovery")
public class CustomerNacosAutoServiceRegistration {

    private boolean registerEnabled;

    @Value("${spring.cloud.nacos.discovery.delay}")
    private long delay;

    @Value("${server.port}")
    private int port;


    @Autowired
    private NacosAutoServiceRegistration nacosAutoServiceRegistration;


    public void delayStart() {
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        executor.schedule(() -> {
            try {
                Method getRegistration = nacosAutoServiceRegistration.getClass().getDeclaredMethod("getRegistration");
                getRegistration.setAccessible(true);
                Object result = getRegistration.invoke(nacosAutoServiceRegistration);
                NacosRegistration registration = (NacosRegistration) result;
                registration.setPort(port);
                registration.getNacosDiscoveryProperties().setRegisterEnabled(true);
                log.info("get registration={}", registration);
                Method register = nacosAutoServiceRegistration.getClass().getSuperclass().getDeclaredMethod("start");
                register.setAccessible(true);
                register.invoke(nacosAutoServiceRegistration);
                log.info("nacos delay register success");
            } catch (Exception e) {
                log.info(" nacos delay register error.", e);
            }
        }, delay, TimeUnit.MILLISECONDS);

    }
}
